  // pages/pay/pay.js
  import request from "../../request/index.js";
  Page({
    data: {
      address: null,
      goodsList: [],
      totalPrice: 0, 
      totalQuantity: 0
    },
    onLoad: function(options) {
      if (options.goodsList && options.totalPrice) {
        let goodsList = JSON.parse(decodeURIComponent(options.goodsList));
        let totalPrice = parseFloat(options.totalPrice).toFixed(2);
        let totalQuantity = goodsList.reduce((acc, item) => acc + item.goods_count, 0);

        this.setData({
          goodsList: goodsList,
          totalPrice: totalPrice,
          totalQuantity: totalQuantity
        });
      }

      if (options.addressInfo) {
        this.setData({
          address: JSON.parse(decodeURIComponent(options.addressInfo))
        });
      }
    },
    chooseAddress: function() {
      let that = this;
      wx.chooseAddress({
        success(res) {
          that.setData({
            address: {
              userName: res.userName,
              telNumber: res.telNumber,
              provinceName: res.provinceName,
              cityName: res.cityName,
              countyName: res.countyName,
              detailInfo: res.detailInfo
            }
          });
        },
        fail(err) {
          console.error('chooseAddress fail:', err);
        }
      });
    },
    toPay: function() {
      const token = wx.getStorageSync('token');
      console.log(token);
      if (token) {
        this.createOrder(token);
      } else {
        wx.navigateTo({
          url: '/pages/auth/auth?from=pay',
        });
      }
    },
    createOrder: function() {
      const token = wx.getStorageSync('token');
      if (!token) {
        wx.navigateTo({
          url: '/pages/auth/auth?frompay'
        });
        return;
      }

      if (!this.data.address) {
        wx.showToast({
          title: '请选择收货地址',
          icon: 'none'
        });
        return;
      }

      const orderData = {
        order_price: this.data.totalPrice,
        consignee_addr: `${this.data.address.provinceName}${this.data.address.cityName}${this.data.address.countyName}${this.data.address.detailInfo}`,
        goods: this.data.goodsList.map(item => ({
          goods_id: item.goods_id,
          goods_number: item.goods_count,
          goods_price: item.goods_price
        }))
      };
      console.log('OrderData:', orderData);
      wx.request({
        url: 'https://api-hmugo-web.itheima.net/api/public/v1/my/orders/create',
        method: 'POST',
        header: { Authorization: token },
        data: orderData,
        success: (res) => {
          console.log(res);
          if (res.statusCode === 200 && res.data.meta.status === 200) {
            const orderNumber = res.data.message.order_number;
            wx.setStorageSync('orderNumber', orderNumber);
            function formatDate(date) {
              const year = date.getFullYear();
              const month = (date.getMonth() + 1).toString().padStart(2, '0');
              const day = date.getDate().toString().padStart(2, '0');
              let hour = date.getHours();
              const minute = date.getMinutes().toString().padStart(2, '0');
              const second = date.getSeconds().toString().padStart(2, '0');
              const period = hour < 12 ? '上午' : '下午';
              hour = hour % 12;
              hour = hour ? hour : 12;
              return `${year}-${month}-${day},${period}${hour}:${minute}:${second}`;
            }
            const orderInfo = {
              orderNumber: orderNumber, 
              orderPrice: this.data.totalPrice, 
              orderTime: formatDate(new Date()) 
            };
            let orders = wx.getStorageSync('orders') || [];
            orders.push(orderInfo);
            wx.setStorageSync('orders', orders);
            console.log(orderNumber);
            wx.request({
              url: 'https://api-hmugo-web.itheima.net/api/public/v1/my/orders/req_unifiedorder',
              method: 'POST',
              header: { Authorization: token },
              data: { order_number: orderNumber },
              success(res) {
                console.log(res);
                if (res.statusCode === 200 && res.data.meta.status === 200) {
                  //const payData = res.data.message;
                  wx.requestPayment({
                    timeStamp: String(Date.now()),
                    nonceStr: 'nonceStr',
                    package: 'prepay_id=wx12345678901234567890123456789012',
                    signType: 'MD5',
                    paySign: 'paySign',
                    success(payRes) {
                      console.log('支付成功', payRes);
                    },
                    fail(payErr) {
                      console.error('支付失败', payErr);
                      wx.showToast({
                        title: '支付失败',
                        icon: 'none'
                      });
                      return;
                    }
                  });
                } else {
                  console.error('获取支付参数失败', res.data);
                }
              },
              fail(err) {
                console.error('请求失败:', err);
              }
          })
          }
        },
      });
    },
  });
